<?php

namespace WeForge\Runtime;

use Swoole\Http\Server;
use Throwable;

class Container
{
    /**
     * Handle the invocation.
     *
     * @param  \Closure $callback
     *
     * @return void
     */
    public static function handleInvocation($callback)
    {
        $server = new Server('0.0.0.0', 9000);

        $server->on('request', function ($request, $response) use ($callback) {
            Context::env('FC_REQUEST_ID', $request->header['x-fc-request-id']);

            register_shutdown_function(function () use ($response) {
                $response->status(500);
                $response->end('Server Error');
            });

            try {
                $callback($request)->send($response);
            } catch (Throwable $error) {
                fwrite(STDERR, sprintf(
                    "Fatal error: %s in %s:%d\nStack trace:\n%s",
                    $error->getMessage(),
                    $error->getFile(),
                    $error->getLine(),
                    $error->getTraceAsString()
                ));

                throw $error;
            } finally {
                Context::destroy();
            }
        });

        $server->start();
    }
}
